import React, { useEffect, useState, useRef, useMemo } from 'react';
import { useDispatch } from 'react-redux';
import ReactECharts from 'echarts-for-react';
import { Form, Input, Button, Toast } from 'antd-mobile';
import { WebSocketService } from '../services/websocket';
import { addRecord } from '../store/detectionSlice';
import type { EChartsInstance } from 'echarts';

const MAX_DISTANCE = 320; // 320mm
const MAX_ANGLE = 180;
const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const DEFAULT_WS_ADDRESS = '192.168.64.129:8080';

// 预定义一些好看的颜色
const COLORS = [
  '#1677ff', // 蓝色
  '#52c41a', // 绿色
  '#722ed1', // 紫色
  '#13c2c2', // 青色
  '#eb2f96', // 粉色
  '#faad14', // 金色
];

interface WebSocketMessage {
  type: 'MEASUREMENT';
  data: [number, number]; // [distance, angle]
}

const Detection: React.FC = () => {
  const dispatch = useDispatch();
  const [wsService] = useState(() => new WebSocketService());
  const [form] = Form.useForm();
  const [currentData, setCurrentData] = useState<[number, number] | null>(null);
  const [isDetecting, setIsDetecting] = useState(false);
  const [isConnecting, setIsConnecting] = useState(false);
  const [maxDistanceValue, setMaxDistanceValue] = useState<number>(0);
  const [currentEmail, setCurrentEmail] = useState<string>('');
  const [isFullscreen, setIsFullscreen] = useState(false);
  const chartRef = useRef<ReactECharts>(null);
  const [dotColor, setDotColor] = useState(COLORS[0]);

  // 每次接收新数据时随机改变颜色
  const getRandomColor = () => {
    const currentIndex = COLORS.indexOf(dotColor);
    const nextIndex = (currentIndex + 1) % COLORS.length;
    return COLORS[nextIndex];
  };

  const getChartOption = () => ({
    tooltip: {
      formatter: (params: any) => {
        const [angle, distance] = params.data;
        const isExceeded = distance > maxDistanceValue;
        return `距离: ${distance}mm${isExceeded ? ' (超出范围)' : ''}<br/>角度: ${angle}°`;
      }
    },
    polar: {
      radius: isFullscreen ? ['0%', '70%'] : ['0%', '80%'],
      center: ['50%', '50%']
    },
    angleAxis: {
      type: 'value',
      max: MAX_ANGLE,
      min: 0,
      startAngle: 90,  // 从正上方开始
      clockwise: true, // 顺时针方向
      axisLabel: {
        formatter: '{value}°',
        fontSize: isFullscreen ? 16 : 14
      },
      splitLine: {
        show: true,
        lineStyle: {
          color: '#E0E0E0',
          width: isFullscreen ? 2 : 1,
          type: 'dashed'
        }
      },
      axisLine: {
        show: true,
        lineStyle: {
          color: '#E0E0E0',
          width: isFullscreen ? 2 : 1
        }
      }
    },
    radiusAxis: {
      type: 'value',
      max: MAX_DISTANCE,
      min: 0,
      interval: 80,
      axisLabel: {
        formatter: '{value}mm',
        fontSize: isFullscreen ? 16 : 14
      },
      splitLine: {
        show: true,
        lineStyle: {
          color: '#E0E0E0',
          width: isFullscreen ? 2 : 1,
          type: 'dashed'
        }
      }
    },
    series: [{
      coordinateSystem: 'polar',
      name: 'Detection',
      type: 'scatter',
      data: currentData ? [[currentData[0], currentData[1]]] : [],
      symbolSize: isFullscreen ? 35 : 25,
      itemStyle: {
        color: dotColor,
        borderColor: '#fff',
        borderWidth: 2,
        shadowBlur: 10,
        shadowColor: 'rgba(0, 0, 0, 0.2)'
      },
      emphasis: {
        itemStyle: {
          shadowBlur: isFullscreen ? 20 : 15,
          shadowColor: 'rgba(0, 0, 0, 0.3)'
        }
      }
    }]
  });

  const handleChartClick = () => {
    const chartInstance = chartRef.current?.getEchartsInstance();
    if (chartInstance) {
      if (!isFullscreen) {
        // 进入全屏
        const chartDom = chartInstance.getDom();
        if (chartDom.requestFullscreen) {
          chartDom.requestFullscreen();
        }
      } else {
        // 退出全屏
        if (document.exitFullscreen) {
          document.exitFullscreen();
        }
      }
    }
  };

  useEffect(() => {
    const handleFullscreenChange = () => {
      setIsFullscreen(!!document.fullscreenElement);
    };

    document.addEventListener('fullscreenchange', handleFullscreenChange);
    return () => {
      document.removeEventListener('fullscreenchange', handleFullscreenChange);
    };
  }, []);

  // 当全屏状态改变时，重新设置图表大小
  useEffect(() => {
    const chartInstance = chartRef.current?.getEchartsInstance();
    if (chartInstance) {
      chartInstance.resize();
    }
  }, [isFullscreen]);

  const handleDetection = async (values: { wsAddress?: string; email: string; maxDistance: string }) => {
    if (!EMAIL_REGEX.test(values.email)) {
      Toast.show({
        content: '请输入有效的邮箱地址'
      });
      return;
    }

    const maxDistance = parseInt(values.maxDistance);
    if (isNaN(maxDistance) || maxDistance > MAX_DISTANCE) {
      Toast.show({
        content: `最大检测距离不能超过${MAX_DISTANCE}mm`
      });
      return;
    }

    // 保存当前设置的最大距离和邮箱
    setMaxDistanceValue(maxDistance);
    setCurrentEmail(values.email);

    try {
      setIsConnecting(true);
      await wsService.connect(values.wsAddress || DEFAULT_WS_ADDRESS, (message: WebSocketMessage) => {
        if (message.type === 'MEASUREMENT') {
          const [distance, angle] = message.data;
          setCurrentData([distance, angle]); // 保存原始数据（毫米）
          setDotColor(getRandomColor());
          
          dispatch(addRecord({
            timestamp: new Date().toISOString(),
            distance: distance,
            angle,
            email: values.email
          }));

          // 只在距离超过设定值时发送通知
          if (distance > maxDistance) { // 直接比较毫米值
            wsService.notifyExceededDistance(values.email, distance);
            Toast.show({
              content: `检测距离 ${distance}mm 超出设定范围 ${maxDistance}mm`,
              position: 'top'
            });
          }
        }
      });

      setIsDetecting(true);
      wsService.startDetection();
    } catch (error) {
      Toast.show({
        content: '连接WebSocket失败，请检查地址是否正确'
      });
      console.error('Failed to connect:', error);
    } finally {
      setIsConnecting(false);
    }
  };

  const handleStop = () => {
    wsService.stopDetection();
    setIsDetecting(false);
  };

  useEffect(() => {
    return () => {
      wsService.disconnect();
    };
  }, []);

  return (
    <div className="detection-container">
      <div className={`chart-container ${isFullscreen ? 'fullscreen' : ''}`}>
        <div className="echarts-container" onClick={handleChartClick}>
          <ReactECharts 
            ref={chartRef}
            option={getChartOption()} 
            style={{ height: '100%', width: '100%' }}
          />
        </div>
        {!isFullscreen && currentData && (
          <div className="current-data">
            <div>当前距离: {currentData[0]}mm {currentData[0] > maxDistanceValue ? '(超出范围)' : ''}</div>
            <div>当前角度: {currentData[1]}°</div>
            {maxDistanceValue > 0 && (
              <div>最大距离: {maxDistanceValue}mm</div>
            )}
          </div>
        )}
      </div>
      
      {!isFullscreen && (
        <div className="form-container">
          <Form
            form={form}
            onFinish={handleDetection}
            layout='vertical'
            footer={
              <Button
                block
                color='primary'
                size='large'
                loading={isConnecting}
                disabled={isConnecting}
                onClick={() => {
                  if (isDetecting) {
                    handleStop();
                  } else {
                    form.submit();
                  }
                }}
              >
                {isConnecting ? '正在连接...' : isDetecting ? '停止检测' : '开始检测'}
              </Button>
            }
          >
            <Form.Item
              label='WebSocket地址'
              name='wsAddress'
            >
              <Input placeholder={`默认使用 ${DEFAULT_WS_ADDRESS}`} />
            </Form.Item>

            <Form.Item
              label='邮箱地址'
              name='email'
              rules={[{ required: true, message: '请输入邮箱地址' }]}
            >
              <Input placeholder='请输入邮箱地址' />
            </Form.Item>

            <Form.Item
              label='最大检测距离'
              name='maxDistance'
              rules={[{ required: true, message: '请输入最大检测距离' }]}
            >
              <Input
                type='number'
                placeholder={`最大值为 ${MAX_DISTANCE}mm`}
                max={MAX_DISTANCE}
              />
            </Form.Item>
          </Form>
        </div>
      )}
    </div>
  );
};

export default Detection; 